package com.jxufe.getData;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class Resouce {
	public static OkHttpClient client = new OkHttpClient();
	public static File file = new File("testWeatherInfo");//写入数据的文件
	public static File signFile = new File("testSignFile");//记录信号量的文件
	public static File cityCode = new File("cityCode");//城市编号文件
	
	public static int size = 3181;//要写入多少城市数据
	public static int count = 0;//计数器
	public static Object lock = new Object();
	
	public static Logger logger = Logger.getLogger("myLog");
	
	public static int cityAmount;//可查的城市总数
	static {
		size = getCityCodes().size();//录入全部城市
		cityAmount = getCityCodes().size();
	}
	
	
	public static MyRunnable getRunnable(String code) {
		MyRunnable runnable = new MyRunnable();
		runnable.setCode(code);
		return runnable;
	}

	public static boolean checkSign(String code) {
		return getAllSignals().contains(code);
	}

	public static List<String> getAllSignals() {
		if (!signFile.exists()) {
			try {
				signFile.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		String string = FileToString(signFile);
		String[] split = string.split("s");
		return Arrays.asList(split);
	}

	public static String FileToString(File file) {
		FileInputStream fis = null;
		String str = "";
		byte[] buffer = new byte[1024];
		int len = 0;
		try {
			fis = new FileInputStream(file);
			while ((len = fis.read(buffer)) != -1) {
				if (len < 1024) {
					byte[] buffer2 = new byte[1024];// 清除缓存
					System.arraycopy(buffer, 0, buffer2, 0, len);
					buffer = buffer2;
				}
				str += new String(buffer).trim();
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				fis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return str;
	}

	public static ArrayList<String> getCityCodes() {
		String str = FileToString(cityCode);
		List<HashMap> list = JSON.parseArray(str, HashMap.class);
		ArrayList<String> arrayList = new ArrayList<String>();
		for (HashMap map : list) { 
			arrayList.add(map.get("id").toString());
		}
		return arrayList;
	}
	
	//Runnable
	public static String run(String url) throws IOException {
		Request request = new Request.Builder().url(url).build();
		Response response = client.newCall(request).execute();
		if (response.isSuccessful()) {
			return response.body().string();
		} else {
			throw new IOException("Unexpected code " + response);
		}
	}
	public static void writeSign(String code) {
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(signFile, true);
			byte[] bytes = (code + "s").getBytes();
			fos.write(bytes);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}
	public static void write(JSONObject json) throws IOException {
		String dataStr = json.get("data").toString();
		List<Weather> weaList = JSONObject.parseArray(dataStr, Weather.class);
//		String string = StringEscapeUtils.unescapeJava(str);
//		System.out.println(string);

		if (!file.exists()) {
			file.createNewFile();
		}
		String cityid = json.get("cityid") == null ? "null" : json.get("cityid").toString();
		String update_time = json.get("update_time") == null ? "null" : json.get("update_time").toString();
		String city = json.get("city") == null ? "null" : json.get("city").toString();
		FileOutputStream fos = new FileOutputStream(file, true);// append
		int week = 0;
		for (Weather weather : weaList) {
			week++;
			weather.setCityid(cityid);
			weather.setUpdate_time(update_time);
			weather.setWeek(week + "");
			weather.setCity(city);
			byte[] bytes = weather.toString().getBytes();
			fos.write(bytes);
		}
		fos.close();
	}
}
